<template>
  <div class="album-detail-page">
    <!-- 返回按钮 -->
    <button class="back-link" @click="goBack">
      <i class="ri-arrow-left-line"></i>
      <span>返回相册</span>
    </button>

    <!-- 相册标题 -->
    <AlbumHeader :album="album" />

    <!-- 图片工具栏 -->
    <PhotosToolbar :viewMode="viewMode" @update:viewMode="viewMode = $event" />

    <!-- 照片列表 -->
    <div class="photos-container">
      <!-- 网格视图 -->
      <PhotoGrid
        v-if="viewMode === 'grid'"
        :photos="album?.photos || []"
        @preview="previewImage"
        @download="downloadPhoto"
      />

      <!-- 瀑布流视图 -->
      <PhotoMasonry
        v-else
        :photos="album?.photos || []"
        @preview="previewImage"
        @download="downloadPhoto"
      />
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>加载中，请稍候...</p>
    </div>

    <!-- 空状态 -->
    <EmptyState v-else-if="!album || album.photos.length === 0" message="暂无照片" />

    <!-- 隐藏的图库容器，用于初始化 ViewerJS -->
    <div class="hidden-gallery" ref="galleryContainer">
      <img
        v-for="(photo, index) in album?.photos"
        :key="index"
        :src="photo.url"
        :alt="photo.title || '照片'"
        class="gallery-item"
        style="display: none"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Viewer from 'viewerjs'
import 'viewerjs/dist/viewer.css'
import AlbumHeader from './components/AlbumHeader.vue'
import PhotosToolbar from './components/PhotosToolbar.vue'
import PhotoGrid from './components/PhotoGrid.vue'
import PhotoMasonry from './components/PhotoMasonry.vue'
import EmptyState from './components/EmptyState.vue'
import { getAlbumPicList } from '@/api/album'

const route = useRoute()
const router = useRouter()
const albumId = computed(() => route.params.id)
const viewMode = ref('grid') // 'grid' 或 'masonry'
const galleryContainer = ref(null)
let viewer = null

const fromPage = computed(() => route.query.fromPage || 1)

// 相册数据
const album = ref(null)
const loading = ref(false)

const goBack = () => {
  router.push({ path: '/albums', query: { page: fromPage.value } })
}

// 数据转换函数：将后端图片数据转换为前端需要的格式
const transformPicData = (apiData) => {
  return apiData.map((item, index) => ({
    id: item.id,
    url: item.picUrl,
    title: item.picName || `照片 ${index + 1}`,
    description: `图片大小: ${formatFileSize(item.picSize)}`,
    aspectRatio: 1, // 默认宽高比，可以根据实际需要调整
    // 保留原始数据用于其他用途
    originalData: item,
  }))
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取相册图片列表
const fetchAlbumPics = async (id) => {
  try {
    loading.value = true
    const pics = await getAlbumPicList(id)

    // 从路由参数中获取相册信息
    const albumInfo = getAlbumInfoFromRoute()

    // 更新相册数据
    album.value = {
      id: id,
      title: albumInfo.title || `相册 ${id}`,
      description: albumInfo.description || '暂无描述',
      date: albumInfo.date || new Date().toISOString().split('T')[0],
      photos: transformPicData(pics || []),
    }

    // 数据加载完成后初始化ViewerJS
    nextTick(() => {
      initViewer()
    })
  } catch (error) {
    console.error('获取相册图片失败:', error)
    // 如果API失败，使用模拟数据作为降级方案
    const albumInfo = getAlbumInfoFromRoute()
    album.value = {
      id: id,
      title: albumInfo.title || `相册 ${id}`,
      description: albumInfo.description || '暂无描述',
      date: albumInfo.date || new Date().toISOString().split('T')[0],
      photos: transformPicData(mockPicData),
    }

    // 降级数据加载完成后也初始化ViewerJS
    nextTick(() => {
      initViewer()
    })
  } finally {
    loading.value = false
  }
}

// 从路由参数中获取相册信息
const getAlbumInfoFromRoute = () => {
  const query = route.query
  return {
    title: query.title || '',
    description: query.description || '',
    date: query.date || '',
  }
}

// 模拟图片数据（作为降级方案）
const mockPicData = [
  {
    id: '1',
    picName: 'sample1.jpg',
    picUrl: 'https://picsum.photos/id/10/1200/800',
    picSize: 49529,
  },
  {
    id: '2',
    picName: 'sample2.jpg',
    picUrl: 'https://picsum.photos/id/11/800/1200',
    picSize: 62341,
  },
  {
    id: '3',
    picName: 'sample3.jpg',
    picUrl: 'https://picsum.photos/id/12/1200/800',
    picSize: 45678,
  },
]

// 初始化 ViewerJS
const initViewer = () => {
  // 确保之前的 viewer 被销毁
  if (viewer) {
    viewer.destroy()
  }

  // 创建新的 viewer 实例
  if (galleryContainer.value) {
    viewer = new Viewer(galleryContainer.value, {
      inline: false,
      navbar: true,
      title: false, // 不显示标题
      toolbar: {
        zoomIn: true,
        zoomOut: true,
        oneToOne: true,
        reset: true,
        prev: true,
        play: false,
        next: true,
        rotateLeft: true,
        rotateRight: true,
        flipHorizontal: true,
        flipVertical: true,
      },
      viewed() {
        // 添加自定义事件处理
      },
    })
    console.log('Viewer initialized', viewer)
  }
}

// 图片预览函数
const previewImage = (index) => {
  if (!album.value || !album.value.photos.length || !viewer) {
    console.warn('预览失败：相册为空或Viewer未初始化')
    return
  }

  console.log('打开图片预览', index)
  viewer.view(index)
}

// 下载照片
const downloadPhoto = async (photo) => {
  if (!photo || !photo.url) return

  try {
    // 获取文件名，如果没有则使用默认名称
    const fileName = photo.title || `photo_${photo.id || Date.now()}`

    // 检查是否是跨域图片
    const isCrossOrigin = !photo.url.startsWith(window.location.origin)

    if (isCrossOrigin) {
      // 跨域图片需要先获取blob
      console.log('正在下载图片...', fileName)
      await downloadCrossOriginImage(photo.url, fileName)
      console.log('图片下载完成:', fileName)
    } else {
      // 同域图片可以直接下载
      console.log('正在下载图片...', fileName)
      downloadSameOriginImage(photo.url, fileName)
      console.log('图片下载完成:', fileName)
    }
  } catch (error) {
    console.error('下载图片失败:', error)
    // 降级方案：在新窗口打开图片
    console.log('下载失败，在新窗口打开图片')
    window.open(photo.url, '_blank')
  }
}

// 下载同域图片
const downloadSameOriginImage = (url, fileName) => {
  const link = document.createElement('a')
  link.href = url
  link.download = fileName
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 下载跨域图片
const downloadCrossOriginImage = async (url, fileName) => {
  try {
    // 使用fetch获取图片数据
    const response = await fetch(url, {
      method: 'GET',
      mode: 'cors',
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 获取blob数据
    const blob = await response.blob()

    // 创建blob URL
    const blobUrl = window.URL.createObjectURL(blob)

    // 创建下载链接
    const link = document.createElement('a')
    link.href = blobUrl
    link.download = fileName
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 清理blob URL
    window.URL.revokeObjectURL(blobUrl)
  } catch (error) {
    console.error('跨域图片下载失败:', error)
    throw error
  }
}

// 监听路由变化
watch(
  () => route.params.id,
  (newId) => {
    if (newId) {
      // 路由变化时重新获取数据
      fetchAlbumPics(newId)
    }
  },
)

// 页面加载时初始化
onMounted(() => {
  console.log('相册详情页已加载', albumId.value)
  if (albumId.value) {
    fetchAlbumPics(albumId.value)
  }
})

// 组件卸载时销毁 viewer
onUnmounted(() => {
  if (viewer) {
    viewer.destroy()
  }
})

defineOptions({ name: 'AlbumDetailPage' })
</script>

<style lang="scss" scoped>
.album-detail-page {
  padding: 2rem 1rem 4rem;
  max-width: 1200px;
  margin: 0 auto;
  position: relative;

  // 隐藏图库容器
  .hidden-gallery {
    display: none;
  }

  // 返回链接
  .back-link {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    color: var(--text-color-secondary);
    text-decoration: none;
    margin-bottom: 2rem;
    font-size: 0.9375rem;
    transition: all 0.2s ease;
    background: none;
    border: none;
    cursor: pointer;

    i {
      font-size: 1.25rem;
    }

    &:hover {
      color: var(--primary-color);
      transform: translateX(-4px);
    }
  }

  // 照片容器
  .photos-container {
    position: relative;
  }

  // 加载状态
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 200px;
    padding: 40px;

    .loading-spinner {
      width: 40px;
      height: 40px;
      border: 3px solid rgba(81, 138, 255, 0.2);
      border-left-color: var(--color-primary);
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 16px;
    }

    p {
      color: var(--text-secondary);
      font-size: 14px;
    }
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

// 响应式调整
@media (max-width: 768px) {
  .album-detail-page {
    padding: 1.5rem 0.75rem 3rem;
  }
}
</style>
